﻿#include "sysoption.h"
#include "ui_sysoption.h"
#include <QMessageBox>
#include "appConfig.h"
#include <QSerialPort>
#include <QDebug>
#include <dialog.h>

t_system_data sysData;

sysOption::sysOption(QWidget *parent,QSerialPort * mPort):
    QWidget(parent),
    ui(new Ui::sysOption)
{
    meWidget = parent;
    port = mPort;
    memset(&sysData,0,sizeof(t_system_data));
    meWidget->setGeometry(10,70,780,500);
    ui->setupUi(this);

    ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_2->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_3->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_4->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_5->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_20->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));

    ui->lineEdit_16->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_17->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_18->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));
    ui->lineEdit_19->setValidator(new QRegExpValidator(QRegExp("[0-9%]+$")));

    checkLog = new Dialog(this);
    checkLog->hide();
    checkLog->setWindowTitle("设备校验");
    autoGetSysFlashTimer = new QTimer(this);
    connect(autoGetSysFlashTimer,SIGNAL(timeout()),this,SLOT(on_autoGetSysFlashTimer_timeout()));
    portInit();
    connect(this,SIGNAL(writeLogText()),this->checkLog,SLOT(appendLogText()));

    connect(ui->lineEdit,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));
    connect(ui->lineEdit_2,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));
    connect(ui->lineEdit_3,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));
    connect(ui->lineEdit_4,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));
    connect(ui->lineEdit_5,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));
    connect(ui->lineEdit_20,SIGNAL(returnPressed()),this,SLOT(lineEditM2ReturnPressed()));

    connect(ui->lineEdit_16,SIGNAL(returnPressed()),this,SLOT(lineEditM1ReturnPressed()));
    connect(ui->lineEdit_17,SIGNAL(returnPressed()),this,SLOT(lineEditM1ReturnPressed()));
    connect(ui->lineEdit_18,SIGNAL(returnPressed()),this,SLOT(lineEditM1ReturnPressed()));
    connect(ui->lineEdit_19,SIGNAL(returnPressed()),this,SLOT(lineEditM1ReturnPressed()));


}

void sysOption::portInit()
{
    waitReadTimer = new QTimer(this);
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
        ui->comboBox->addItem(info.portName()+" "+info.description());
    }
    connect(port,SIGNAL(readyRead()),this,SLOT(serialPortReadyRead()));
    connect(waitReadTimer,SIGNAL(timeout()),this,SLOT(waitReadTimerTimeOut()));
}

bool sysOption::portConfig(bool status)
{
    QStringList list = ui->comboBox->currentText().split(" ");
    port->setPortName(list[0]);
    port->setBaudRate(ui->comboBox_2->currentText().toInt());
    port->setDataBits(QSerialPort::Data8);
    port->setParity(QSerialPort::NoParity);
    port->setStopBits(QSerialPort::OneStop);
    port->setFlowControl(QSerialPort::NoFlowControl);
    if(status){
        if(!port->open(QIODevice::ReadWrite)){
            QMessageBox::warning(NULL, "错误","串口无法打开！可能串口已经被占用！");
            return false;
        }
    }else{
         port->close();
         return true;
    }
    return true;
}

uint8_t sysOption::checkXOR(char *data, int length)
{
    uint8_t checksum = 0;
    for (int i = 0; i < length; i++) {
        checksum ^= data[i];
    }
    return checksum;
}


/// @brief 串口数据解析
/// @param data
/// @param len
void sysOption::procPortData(uint8_t *data, uint32_t len)
{
    int temp_index;
    int Val,Val_H;
    if(data[0] != 0X77 || data[1] != 0XEE || data[len-1] != 0XEF){
        return;
    }
    if(checkXOR((char *)data,len-2) != data[len - 2]){
        return;
    }
    uint32_t data_len = 0;
    memcpy(&data_len,&data[6],sizeof(data_len));
    //日志信息相关
    if(data[10] == 0X0A){
        logQue.enqueue(QString::fromLocal8Bit((const char *)&data[11],data_len - 1));
        if(checkLog->isHidden()){
            checkLog->show();
        }
    }
    if(data[10] == 0X01){
        memcpy(&sysData.now,&data[11],sizeof(sysData.now));
        emit updateSysData();
    }
    if(data[10] == 0X02){
        memcpy(&sysData.flash,&data[11],sizeof(sysData.flash));
        //变焦信息
        ui->lineEdit->setPlaceholderText(QString::number( sysData.flash.zoom_adjust[0]));
        ui->lineEdit_2->setPlaceholderText(QString::number( sysData.flash.zoom_adjust[1]));
        ui->lineEdit_3->setPlaceholderText(QString::number( sysData.flash.zoom_adjust[2]));
        ui->lineEdit_4->setPlaceholderText(QString::number( sysData.flash.zoom_adjust[3]));
        ui->lineEdit_5->setPlaceholderText(QString::number( sysData.flash.zoom_adjust[4]));
        //温度补偿
        if(sysData.flash.temp_flag){
            ui->radioButton->setChecked(true);
            ui->radioButton_2->setChecked(false);
        }else{
            ui->radioButton->setChecked(false);
            ui->radioButton_2->setChecked(true);
        }
        //温度补偿有效位
        if(sysData.flash.temp_data_en){
            ui->radioButton_3->setChecked(false);
            ui->radioButton_4->setChecked(true);
        }else{
            ui->radioButton_3->setChecked(true);
            ui->radioButton_4->setChecked(false);
        }
        //温度的对应数据
        temp_index = ui->comboBox_5->currentIndex();
        ui->lineEdit_16->setPlaceholderText(QString::number( sysData.flash.adjust[temp_index][0]));
        ui->lineEdit_17->setPlaceholderText(QString::number( sysData.flash.adjust[temp_index][1]));

        ui->lineEdit_20->setPlaceholderText(QString::number( sysData.flash.InteractZoom));




        ui->horizontalSlider_2->setValue( sysData.flash.InteractZoom  / sysData.now.max_m2_tick);

        ui->lineEdit_18->setPlaceholderText(QString::number( sysData.flash.InteractFocus));
        ui->lineEdit_19->setPlaceholderText(QString::number( sysData.flash.InteractFocus_1));

        if(sysData.flash.Interact_En){
            ui->radioButton_5->setChecked(true);
            ui->radioButton_6->setChecked(false);
        }else{
            ui->radioButton_5->setChecked(false);
            ui->radioButton_6->setChecked(true);
        }

        Val = (float )sysData.flash.InteractZoom / (float )sysData.now.max_m2_tick * 100;
        Val_H = std::round(Val);        //小数部分四舍五入
        ui->horizontalSlider_2->setValue(Val_H);
    }
}

sysOption::~sysOption()
{
    delete ui;
}

void sysOption::on_pushButton_2_clicked()
{
    QString message = QString("%1 %2 8,1,NoParity,NoFlowControl 已%3").arg(ui->comboBox->currentText()).arg(ui->comboBox_2->currentText()).arg(ui->pushButton_2->text());
    if(port->isOpen() == false){
        if(portConfig(true) == true){
            ui->pushButton_2->setText("关闭");
            ui->pushButton_2->setStyleSheet("background-color: rgb(85, 170, 0);color: rgb(255, 255, 255);");
            ui->comboBox->setEnabled(!port->isOpen());
            ui->comboBox_2->setEnabled(!port->isOpen());
            ui->pushButton->setEnabled(!port->isOpen());
            emit setPortStatus(true);
            emit setStatusMessage(message);
            autoGetSysFlashTimer->start(500);
        }
    }else{
        if(portConfig(false) == true){
           ui->pushButton_2->setText("打开");
           ui->pushButton_2->setStyleSheet("background-color: rgb(210, 30, 6);color: rgb(255, 255, 255);");
           ui->comboBox->setEnabled(!port->isOpen());
           ui->comboBox_2->setEnabled(!port->isOpen());
           ui->pushButton->setEnabled(!port->isOpen());
           emit setPortStatus(false);
           emit setStatusMessage(message);
        }
    }
}

void sysOption::on_pushButton_clicked()
{
    ui->comboBox->clear();
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
        ui->comboBox->addItem(info.portName()+" "+info.description());
    }
}

void sysOption::serialPortReadyRead()
{
  waitReadTimer->start(20);
}

//变焦设定
void sysOption::on_pushButton_5_clicked()
{
    uint32_t zoomData[5];
    uint8_t zoomOpCmd[34];
    if(ui->lineEdit->placeholderText().isEmpty() || ui->lineEdit_2->placeholderText().isEmpty() ||
            ui->lineEdit_3->placeholderText().isEmpty() || ui->lineEdit_4->placeholderText().isEmpty() ||
            ui->lineEdit_5->placeholderText().isEmpty()){
        QMessageBox::about(NULL,"错误","请输入设定值,按回车键结束");
        return;
    }
    zoomData[0] =  ui->lineEdit->placeholderText().toInt();
    zoomData[1] =  ui->lineEdit_2->placeholderText().toInt();
    zoomData[2] =  ui->lineEdit_3->placeholderText().toInt();
    zoomData[3] =  ui->lineEdit_4->placeholderText().toInt();
    zoomData[4] =  ui->lineEdit_5->placeholderText().toInt();
    zoomOpCmd[0] = 0X77;zoomOpCmd[1] = 0XEE;
    zoomOpCmd[2] = 0XFF;zoomOpCmd[3] = 0XFF;zoomOpCmd[4] = 0XFF;zoomOpCmd[5] = 0XFF;
    zoomOpCmd[6] = 0X16;zoomOpCmd[7] = 0X00;zoomOpCmd[8] = 0X16;zoomOpCmd[9] = 0X00;
    zoomOpCmd[10] = 0X02;zoomOpCmd[11] = 0XFF;
    memcpy(&zoomOpCmd[12],zoomData,sizeof (zoomData));
    zoomOpCmd[32] = checkXOR((char *)zoomOpCmd,32);
    zoomOpCmd[33] = 0XEF;
    port->write((const char *)zoomOpCmd,sizeof(zoomOpCmd));
    emit WaitMs(200);
}


//温度 combox选择
void sysOption::on_comboBox_5_currentIndexChanged(int index)
{
    if(index >= 10){
        return;
    }

    QString dataNo0 = QString::number(sysData.flash.adjust[index][0]);
    QString dataNo1 = QString::number(sysData.flash.adjust[index][1]);

    if(~sysData.flash.adjust[index][0] == 0X00){
        ui->lineEdit_16->setPlaceholderText("");
        return ;
    }
    if(~sysData.flash.adjust[index][1] == 0X00){
        ui->lineEdit_17->setPlaceholderText("");
        return ;
    }

    ui->lineEdit_16->setPlaceholderText(dataNo0);
    ui->lineEdit_17->setPlaceholderText(dataNo1);
}

void sysOption::on_pushButton_9_clicked()
{
    unsigned char sysResetCmd[14] = {0X77,0XEE,0XFF,0XFF,0XFF,0XFF,0X02,0X00,0X00,0X00,0X06,0X01,0X00,0XEF};
    sysResetCmd[12] = checkXOR((char * )sysResetCmd,sizeof(sysResetCmd) - 2);
    port->write((const char *)sysResetCmd,sizeof(sysResetCmd));
    emit WaitMs(200);
    logQue.clear();
    emit writeLogText();
}


//获取变焦信息
void sysOption::on_pushButton_3_clicked()
{
    unsigned char getZoomFlashCmd[14] = {0X77,0XEE,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X02,0X09,0X01,0X00,0XEF};
    getZoomFlashCmd[12] = checkXOR((char * )getZoomFlashCmd,sizeof(getZoomFlashCmd) - 2);
    port->write((const char *)getZoomFlashCmd,sizeof(getZoomFlashCmd));
    emit WaitMs(200);
}

void sysOption::waitReadTimerTimeOut()
{
    waitReadTimer->stop();
    QByteArray buf = port->readAll();
    procPortData((uint8_t *)buf.data(), buf.length());
}

void sysOption::lineEditM2ReturnPressed()
{
    float  Val = 0;
    int Val_H= 0;
    QLineEdit * lineEdit = qobject_cast<QLineEdit *>(sender());
    QString text = lineEdit->text();
    if(textCheck(text,sysData.now.max_m2_tick) == false){
        text.clear();
    }
    lineEdit->setPlaceholderText(text);
    lineEdit->setText("");
    if(lineEdit->objectName() == "lineEdit_20"){
        Val = (float )text.toInt() / (float )sysData.now.max_m2_tick * 100;
        Val_H = std::round(Val);        //小数部分四舍五入
        ui->horizontalSlider_2->setValue(Val_H);
    }
}

void sysOption::lineEditM1ReturnPressed()
{
    QLineEdit * lineEdit = qobject_cast<QLineEdit *>(sender());
    QString text = lineEdit->text();
    if(textCheck(text,sysData.now.max_m1_tick) == false){
        text.clear();
    }
    lineEdit->setPlaceholderText(text);
    lineEdit->setText("");
}


//05 温度 数据1(4byte) 数据2(4byte) 开关(1byte) 有效位(1byte)
//2 + 4 + 4 + 12 + 1 + 1
void sysOption::on_pushButton_7_clicked()
{
    uint32_t tempData[2];
    uint8_t tempCmd[24];
    uint8_t SW = 0X00;
    uint8_t dataEn = 0X00;

    if(ui->lineEdit_16->placeholderText().isEmpty() || ui->lineEdit_17->placeholderText().isEmpty()){
        QMessageBox::about(NULL,"错误","请输入设定值,按回车键结束");
        return;
    }

    ui->radioButton_3->isChecked() ? dataEn = 0X00 : dataEn = 0X01;
    ui->radioButton->isChecked() ? SW = 0x01 : SW = 0x00;

    tempData[0] = ui->lineEdit_16->text().toInt();
    tempData[1] = ui->lineEdit_17->text().toInt();

    int temp = ui->comboBox_5->currentIndex() * 10;
    tempCmd[0] = 0X77;tempCmd[1] = 0XEE;
    tempCmd[2] = 0XFF;tempCmd[3] = 0XFF;tempCmd[4] = 0XFF;tempCmd[5] = 0XFF;
    tempCmd[6] = 0X0C;tempCmd[7] = 0X00;tempCmd[8] = 0X00;tempCmd[9] = 0X00;
    tempCmd[10] = 0x05;tempCmd[11] = temp;
    memcpy(&tempCmd[12],tempData,sizeof(tempData));
    tempCmd[20] = SW;tempCmd[21] = dataEn;
    tempCmd[22] = checkXOR((char *)tempCmd,22);
    tempCmd[23] = 0XEF;
    port->write((const char *)tempCmd,sizeof(tempCmd));
    emit WaitMs(200);
}

void sysOption::on_pushButton_8_clicked()
{
    uint8_t SW = 0;
    uint32_t Interact[3];
    uint8_t InteractCmd[26];
    if(ui->lineEdit_18->placeholderText().isEmpty() || ui->lineEdit_19->placeholderText().isEmpty()
         || ui->lineEdit_20->placeholderText().isEmpty()){
        QMessageBox::about(NULL,"错误","请输入设定值,按回车键结束");
        return;
    }
    ui->radioButton_5->isChecked() ? SW = 0x01 : SW = 0x00;
    Interact[0] = ui->lineEdit_20->placeholderText().toInt();
    Interact[1] = ui->lineEdit_18->placeholderText().toInt();
    Interact[2] = ui->lineEdit_19->placeholderText().toInt();
    InteractCmd[0] = 0X77;InteractCmd[1] = 0XEE;
    InteractCmd[2] = 0XFF;InteractCmd[3] = 0XFF;InteractCmd[4] = 0XFF;InteractCmd[5] = 0XFF;
    InteractCmd[6] = 0X1A;InteractCmd[7] = 0X00;InteractCmd[8] = 0X00;InteractCmd[9] = 0X00;
    InteractCmd[10] = 0x08;
    memcpy(&InteractCmd[11],Interact,sizeof(Interact));
    InteractCmd[23] = SW;
    InteractCmd[24] = checkXOR((char *)InteractCmd,24);
    InteractCmd[25] = 0XEF;
    port->write((const char *)InteractCmd,sizeof(InteractCmd));
    emit WaitMs(200);
}

void sysOption::on_horizontalSlider_2_valueChanged(int value)
{
    int ZoomVal = sysData.now.max_m2_tick * value / 100;
    ui->lineEdit_20->setPlaceholderText(QString::number(ZoomVal));
}

void sysOption::on_pushButton_10_clicked()
{
    unsigned char sysResetCmd[14] = {0X77,0XEE,0XFF,0XFF,0XFF,0XFF,0X02,0X00,0X00,0X00,0X06,0X02,0X00,0XEF};
    sysResetCmd[12] = checkXOR((char * )sysResetCmd,sizeof(sysResetCmd) - 2);
    port->write((const char *)sysResetCmd,sizeof(sysResetCmd));
    emit WaitMs(200);
}

void sysOption::montorStop()
{
    unsigned char sysStopCmd[13] = {0X77,0XEE,0XFF,0XFF,0XFF,0XFF,0X01,0X00,0X00,0X00,0X00,0X00,0XEF};
    sysStopCmd[11] = checkXOR((char * )sysStopCmd,sizeof(sysStopCmd) - 2);
    port->write((const char *)sysStopCmd,sizeof(sysStopCmd));
    emit WaitMs(200);
}

void sysOption::on_autoGetSysFlashTimer_timeout()
{
    autoGetSysFlashTimer->stop();
    unsigned char getZoomFlashCmd[14] = {0X77,0XEE,0XFF,0XFF,0XFF,0XFF,0X00,0X00,0X00,0X02,0X09,0X01,0X00,0XEF};
    getZoomFlashCmd[12] = checkXOR((char * )getZoomFlashCmd,sizeof(getZoomFlashCmd) - 2);
    port->write((const char *)getZoomFlashCmd,sizeof(getZoomFlashCmd));
    emit WaitMs(200);
}
